package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zcf
 */
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserOrderMapper userOrderMapper;

    /**
     * 定时关闭超时未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void closeOrder() {
        log.info("定时关闭超时未支付的订单");
        //查询超时15分钟，未支付的订单
        //1.拿到当前时间15分钟之前的
        LocalDateTime BeForeTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.list(Orders.PENDING_PAYMENT, BeForeTime);
        if (list != null && list.size() > 0) {
           list.stream().forEach(
                   orders -> {
                       orders.setStatus(Orders.CANCELLED);
                       orders.setCancelReason("订单超时，自动取消");
                       orders.setCancelTime(LocalDateTime.now());
                      userOrderMapper.update(orders);
                   }
           );
        }
    }


    /**
     * 定时完成派送中却没有点击完成的订单
     *
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void completeOrder() {
        log.info("定时完成派送中却没有点击完成的订单");
        //查询派送中的订单
        //1. 2小时之前的时间
        LocalDateTime BeForeTime = LocalDateTime.now().plusHours(-2);
        List<Orders> list = orderMapper.list(Orders.DELIVERY_IN_PROGRESS, BeForeTime);
        if (list != null && list.size() > 0) {
            list.stream().forEach(
                    orders -> {
                        orders.setStatus(Orders.COMPLETED);
                        orders.setDeliveryTime(LocalDateTime.now());
                       userOrderMapper.update(orders);
                    }
            );
        }
    }
}
